import 'package:flutter/material.dart';

class RefreshLoadMorePage extends StatefulWidget {
  @override
  _RefreshLoadMorePageState createState() => _RefreshLoadMorePageState();
}

class _RefreshLoadMorePageState extends State<RefreshLoadMorePage> {
  List<String> items = List.generate(15, (index) => "Item $index");
  bool isLoading = false;

  Future<void> _onRefresh() async {
    await Future.delayed(Duration(seconds: 2)); // 模拟网络请求
    setState(() {
      items = List.generate(15, (index) => "Item $index"); // 刷新数据
    });
  }

  Future<void> _loadMore() async {
    if (isLoading) return;
    setState(() {
      isLoading = true;
    });

    await Future.delayed(Duration(seconds: 2)); // 模拟网络请求
    final int itemCount = items.length;
    final newItems = List.generate(5, (index) => "Item ${itemCount + index}");

    setState(() {
      items.addAll(newItems);
      isLoading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("下拉刷新 & 上拉加载")),
      body: RefreshIndicator(
        onRefresh: _onRefresh,
        child: ListView.builder(
          itemCount: items.length + 1, // 多加一项用于显示加载指示器
          itemBuilder: (context, index) {
            if (index < items.length) {
              return ListTile(title: Text(items[index]));
            } else {
              return Padding(
                padding: const EdgeInsets.symmetric(vertical: 32.0),
                child: Center(
                  child:
                      !isLoading
                          ? ElevatedButton(
                            onPressed: _loadMore,
                            child: Text("加载更多"),
                          )
                          : CircularProgressIndicator(),
                ),
              );
            }
          },
        ),
      ),
    );
  }
}
